MongoDB C# 查询和分组

一般查询 Find

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//定义查询条件
var fb = Builders<QcdOrder>.Filter;
var filter = fb.Eq(m => m.IsDelete, false);

//查询条件组合
//日期过滤
filter &= fb.Gt(o => o.CreatedOn, start);
filter &= fb.Lt(o => o.CreatedOn, end);
//正则表达式
filter &= fb.Regex(m => m.SendShortName, new BsonRegularExpression(new Regex(keyword, RegexOptions.IgnoreCase)))
| fb.Regex(m => m.SendFullName, new BsonRegularExpression(new Regex(keyword, RegexOptions.IgnoreCase)))
| fb.Regex(m => m.ReceiveShortName, new BsonRegularExpression(new Regex(keyword, RegexOptions.IgnoreCase)))
| fb.Regex(m => m.ReceiveFullName, new BsonRegularExpression(new Regex(keyword, RegexOptions.IgnoreCase)));

//统计总记录数
int count = (int)mongoOrder.Find(filter).Count();

//排序
var sb = Builders<QcdOrder>.Sort;
var sort = sb.Descending(m => m.AutoId);

//计算页面
if (page > pageCount)
{
page = pageCount;

}
var skip = (page - 1) * pageSize;
var taking = pageSize;

if (page == pageCount)
taking = count - skip;

//查询数据
var list = mongoOrder.Find(filter).Sort(sort).Skip(skip).Limit(taking).ToList();

注意:

  1. 使用Builders<QcdOrder>对象的静态属性来获得一系列的Builder,例如:Filter,Project 等;
  2. 使用Builders<QcdOrder>.Filter来初始化Filter
  3. 使用重载操作符&|进行AndOr操作;

聚合 Aggregation

查询语句示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
db.getCollection('QcdOrder').aggregate([
//{ $project: { 'Fee100': 1}},
{ $match : {
IsDelete : false,
CreatedOn : {
$gt : new Date("2017-01-01"),
$lt : new Date("2017-03-22"),
},
}
},
{ $group :
{
_id : null , //分组_id设置为null,不进行分组操作,统计所有的记录
Count : {$sum : 1},
sumTotalAccount100: {$sum : '$TotalAccount100'},
sumFee100 : {$sum : '$Fee100'},
sumServicesGoods : {$sum : '$ServicesGoodsTotalQuantity'},
sumMemberPayFee : {$sum : '$MemberPayFee100'},
}
}
])

c#代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//设置_id为'null',必须要是一个字符串,不能是null值
var group = BsonDocument.Parse(@"
{
_id : 'null',
sumTotalAccount100: {$sum : '$TotalAccount100'},
sumFee100 : {$sum : '$Fee100'},
sumServicesGoods : {$sum : '$ServicesGoodsTotalQuantity'},
sumMemberPayFee : {$sum : '$MemberPayFee100'}
}");
//聚合统计
var ag = mongoOrder.Aggregate()
.Match(filter) //查询条件
.Group(group)
.ToList();

注意:聚合操作不需要分组时,C#无法通过表达式来设定idnull,只能通过BsonDocument.Parse()方法来转换一个group节。